//
//  ChainLoginVC.m
//  Chain
//
//  Created by zhaosh on 2018/4/9.
//  Copyright © 2018年 zhaosh. All rights reserved.
//

#import "ChainLoginVC.h"
#import "IQKeyboardManager.h"
#import "AppDelegate.h"
#import "ChainProtocolAgreeVC.h"

@interface ChainLoginVC()<UITextFieldDelegate>{
    dispatch_source_t timer;
}
@property(nonatomic,strong) UIView *teleBgview;
@property(nonatomic,strong) UIView *verifyBgview;
@property(nonatomic,strong) UITextField *teleField;
@property(nonatomic,strong) UITextField *verifyField;
@property(nonatomic,strong) UIButton *sureButton;
@property(nonatomic,assign) float field_text_width;
@property(nonatomic,strong) UILabel *placeHolderLabel;
@end

@implementation ChainLoginVC

-(void)loadView{
    [super loadView];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    scrollView.contentSize =CGSizeMake(self.view.width, self.view.height+80);
    scrollView.scrollEnabled=NO;
    self.view = scrollView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CGFLOAT_MIN * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.navigationController setNavigationBarHidden:YES animated:NO];
    });
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewDidLoad {
    self.navigationController.navigationBar.hidden=YES;
    self.fd_interactivePopDisabled=YES;
    
    [super viewDidLoad];
    IQKeyboardReturnKeyHandler *retuenKeyHandler = [[IQKeyboardReturnKeyHandler alloc]initWithViewController:self];
    retuenKeyHandler.lastTextFieldReturnKeyType =UIReturnKeyDone;
    
    UIButton *closeButton=[[UIButton alloc] initWithFrame:CGRectMake(30,80,15,15)];
    [closeButton setBackgroundImage:[UIImage imageNamed:@"mine_close"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(doTouchcloseButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: closeButton];
    
    [self createLoginView];
}

-(void)createLoginView{
    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake((self.view.width-90)/2, 120, 90, 90)];
    imageView.image=[UIImage imageNamed:@"AppIcon"];
    imageView.layer.cornerRadius =5;
    imageView.layer.masksToBounds =YES;
    [self.view addSubview:imageView];
    
    self.teleBgview=[[UIView alloc] initWithFrame:CGRectMake(30, imageView.bottom+75,self.view.width-60, 50)];
    self.teleBgview.backgroundColor=[UIColor whiteColor];
    self.teleBgview.layer.masksToBounds = YES;
    self.teleBgview.layer.cornerRadius=5;
    self.teleBgview.layer.borderWidth=1;
    self.teleBgview.layer.borderColor=[UIColor colorWithHexString:@"#c1c2c3"].CGColor;
    [self.view addSubview:self.teleBgview];
    
    UILabel *preLabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 28, 35)];
    preLabel.backgroundColor=[UIColor clearColor];
    preLabel.textColor=LableTextColor333;
    preLabel.font=[UIFont systemFontOfSize:18];
    preLabel.text=@"86"; 
    [self.teleBgview addSubview:preLabel];
    
    UIView *lineview=[[UIView alloc] initWithFrame:CGRectMake(preLabel.right+5, 10,1,30)];
    lineview.backgroundColor=LableTextColor333;
    [self.teleBgview addSubview:lineview];
    
    self.teleField=[[UITextField alloc] initWithFrame:CGRectMake(lineview.right+10, 4,self.teleBgview.width-8-lineview.right-5, 42)];
    self.teleField.clearButtonMode = UITextFieldViewModeNever;
    self.teleField.placeholder=@"请输入手机号";
    self.teleField.borderStyle=UITextBorderStyleNone;
    self.teleField.backgroundColor=[UIColor clearColor];
    self.teleField.textColor = LableTextColor333;
    self.teleField.delegate=self;
    self.teleField.font = FONT_LB(18.0);
    self.teleField.layer.masksToBounds = YES;
    [self.teleField addTarget:self action:@selector(teleFieldViewDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.teleField.keyboardType=UIKeyboardTypeNumberPad;
    [self.teleBgview addSubview:self.teleField];
    
    self.verifyBgview=[[UIView alloc] initWithFrame:CGRectMake(30,self.teleBgview.bottom,self.view.width, 51)];
    self.verifyBgview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.verifyBgview];
    
    self.placeHolderLabel=[[UILabel alloc] initWithFrame:CGRectMake(17, 0,self.verifyBgview.width+3, 50)];
    self.placeHolderLabel.backgroundColor=[UIColor clearColor];
    self.placeHolderLabel.textColor=LableTextColor999;
    self.placeHolderLabel.font=[UIFont systemFontOfSize:18];
    [self.verifyBgview addSubview:self.placeHolderLabel];
    
    self.verifyField=[[UITextField alloc] initWithFrame:CGRectMake(20, 0,self.verifyBgview.width, 50)];
    self.verifyField.clearButtonMode = UITextFieldViewModeNever;
    self.verifyField.borderStyle=UITextBorderStyleNone;
    self.verifyField.backgroundColor=[UIColor clearColor];
    self.verifyField.textColor =LableTextColor333;
    self.verifyField.delegate=self;
    self.verifyField.font = FONT_LB(18.0);
    self.verifyField.layer.masksToBounds = YES;
    self.verifyField.returnKeyType = UIReturnKeyNext ;
    self.verifyField.keyboardType=UIKeyboardTypeNumberPad;
    [self.verifyField addTarget:self action:@selector(verifyFieldViewDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.verifyBgview addSubview:self.verifyField];
    [self.verifyField limitTextFieldWithLength:6];
    
    self.field_text_width=(self.view.width-70-8*5)/6;
    
    NSDictionary *attrsDictionary =@{
                                     NSFontAttributeName:self.placeHolderLabel.font,
                                     NSKernAttributeName:[NSNumber numberWithFloat:self.field_text_width-11]//这里修改字符间距
                                     };
    self.placeHolderLabel.attributedText=[[NSAttributedString alloc]initWithString:@"请输入验证码" attributes:attrsDictionary];
    
    for (int i=0; i<6; i++) {
        UIView *vi=[[UIView alloc] initWithFrame:CGRectMake((self.field_text_width+8)*i, 50, self.field_text_width, 1)];
        vi.backgroundColor=[UIColor colorWithHexString:@"#c1c2c3"];
        vi.tag=i+1;
        [self.verifyBgview addSubview:vi];
    }
    self.verifyBgview.alpha=0;
    
    self.sureButton=[[UIButton alloc] initWithFrame:CGRectMake(30, self.teleBgview.bottom+30, self.view.width-60, 50)];
    [self.sureButton setBackgroundColor:[UIColor colorWithHexString:@"#ce0d0d"]];
    self.sureButton.titleLabel.textColor=[UIColor whiteColor];
    self.sureButton.titleLabel.font=[UIFont boldSystemFontOfSize:16];
    [self.sureButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.sureButton addTarget:self action:@selector(doTouchSureBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.sureButton.layer.masksToBounds = YES;
    self.sureButton.layer.cornerRadius=5;
    [self.view addSubview:self.sureButton];
    
    UIButton *agreeButton=[[UIButton alloc] initWithFrame:CGRectMake((self.view.width-160-30)/2,self.view.height-80, 15, 15)];
    [agreeButton setBackgroundImage:[UIImage imageNamed:@"mine_agree"] forState:UIControlStateNormal];
    [agreeButton addTarget:self action:@selector(doTouchagreeBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: agreeButton];
    
    UIButton *agreeLabelBtn=[[UIButton alloc] initWithFrame:CGRectMake(agreeButton.right+15, agreeButton.top-2, 160, 18)];
    agreeLabelBtn.backgroundColor=[UIColor clearColor];
    [agreeLabelBtn setTitleColor:LableTextColor666 forState:UIControlStateNormal];
    agreeLabelBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    [agreeLabelBtn addTarget:self action:@selector(doTouchShowTextBtn:) forControlEvents:UIControlEventTouchUpInside];
    [agreeLabelBtn  setTitle:@"我已阅读同意\"用户协议\"" forState:UIControlStateNormal];
    [self.view addSubview:agreeLabelBtn];
}

-(void)doTouchcloseButton:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:NO];
    APPDELEGATE.tabBarControllerConfig.tabBarController.selectedIndex=0;
}

-(void)doTouchShowTextBtn:(UIButton *)button{
    ChainProtocolAgreeVC *protocolAgreeVC =[[ChainProtocolAgreeVC alloc] init];
    [self.navigationController pushViewController:protocolAgreeVC animated:YES];
}

-(void)doTouchagreeBtn:(UIButton *)button{
    if ([[button backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"mine_agree"]]) {
        [button setBackgroundImage:[UIImage imageNamed:@"mine_agree_selected"] forState:UIControlStateNormal];
    }else{
        [button setBackgroundImage:[UIImage imageNamed:@"mine_agree"] forState:UIControlStateNormal];
    }
}

-(void)doTouchSureBtn:(UIButton *)button{
    if ([[button titleForState:UIControlStateNormal] isEqualToString:@"发送验证码"]) {
        if (![CheckDataTool checkForMobilePhoneNo:self.teleField.text]) {
            [MBProgressHUD  showMessage:@"请输入正确格式的手机号" ToView:nil RemainTime:0.5];
            return;
        }
        self.verifyBgview.alpha=1;
        self.sureButton.frame = CGRectMake(30, self.verifyBgview.bottom+30, self.view.width-60, 50);
        [self countDownAction:button];
        [self.sureButton setBackgroundColor:[UIColor colorWithHexString:@"#cccccc"]];
        
        [self sendCode];
    }else if ([[button titleForState:UIControlStateNormal] isEqualToString:@"登录"]){
        [self loginByCode];
    }
}

-(void)teleFieldViewDidChange:(UITextField *)textView{
    
    [self.sureButton setBackgroundColor:[UIColor colorWithHexString:@"#ce0d0d"]];
    [self.sureButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    self.sureButton.userInteractionEnabled = YES;
    if (timer) {
        dispatch_cancel(timer);
    }
}

//监视字符长度的变化
-(void)verifyFieldViewDidChange:(UITextField *)textView{
    NSInteger length = textView.text.length;
    if (length>0) {
        self.placeHolderLabel.alpha=0;
    }else{
        self.placeHolderLabel.alpha=1;
    }
    if (length>=6) {
        self.verifyField.tintColor =[UIColor clearColor];
    }else{
        self.verifyField.tintColor=nil;
    }
    if (length > 6) {
        textView.text = [textView.text substringToIndex:6];
    }
    NSDictionary *attrsDictionary =@{
                                     NSFontAttributeName:textView.font,
                                     NSKernAttributeName:[NSNumber numberWithFloat:self.field_text_width-3]//这里修改字符间距
                                     };
    textView.attributedText=[[NSAttributedString alloc]initWithString:textView.text attributes:attrsDictionary];
    
    NSInteger textLength=textView.attributedText.length;
    if (textLength>0) {
        for (int i=1; i<7; i++) {
            UIView *vi=[self.verifyBgview viewWithTag:i];
            if (i<=textLength) {
                vi.backgroundColor=LableTextColor333;
            }else{
                vi.backgroundColor=[UIColor colorWithHexString:@"#c1c2c3"];
            }
        }
    }
    if (length==6) {
        dispatch_cancel(timer);
        [self.sureButton setBackgroundColor:[UIColor colorWithHexString:@"#ce0d0d"]];
        [self.sureButton setTitle:@"登录" forState:UIControlStateNormal];
        self.sureButton.userInteractionEnabled = YES;
    }
}

-(void)sendCode{
    NSDictionary *params = @{@"mobile":self.teleField.text};
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,SendCode_Url];
    [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
        NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
        if (error) {
            NSString *message=[info objectForKey:@"message"];
            [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.8];
        }else{}
    }];
}

-(void)loginByCode{
    [MBProgressHUD showLoadingToView:self.view];
    
    NSDictionary *params = @{@"mobile":self.teleField.text,
                             @"code":[self.verifyField.text removeAllSpace]
                             };
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,Login_Url];
    __weak typeof(self)weakSelf = self;
    [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
        [MBProgressHUD  hideHUDForView:self.view];
        NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
        if (error) {
            [weakSelf shakeAnimationForView:self.verifyBgview];
        }else{
            NSString *success=[NSString stringWithFormat:@"%@",[info objectForKey:@"status"]];
            NSString *shortMessageErrorCode =[NSString stringWithFormat:@"%@",[info objectForKey:@"shortMessageErrorCode"]];
            NSString *message=[info objectForKey:@"message"];
            
            
            if([success isEqualToString:@"OK"]){
                NSString *sessionID=[NSString stringWithFormat:@"%@",[info valueForKeyPath:@"entity.sessionId"]];
                NSString *userId=[NSString stringWithFormat:@"%@",[info valueForKeyPath:@"entity.id"]];
                NSString *nickName=[NSString stringWithFormat:@"%@",[info valueForKeyPath:@"entity.nickName"]];
                if (![sessionID isBlankString]) {
                    [[NSUserDefaults standardUserDefaults] setObject:sessionID forKey:@"sessionId"];
                }
                if (![userId isBlankString]) {
                    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
                }
                if (![nickName isBlankString]) {
                    [[NSUserDefaults standardUserDefaults] setObject:nickName forKey:@"nickName"];
                }
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [weakSelf.navigationController popViewControllerAnimated:NO];
            }else if ([shortMessageErrorCode isEqualToString:@"0"]) {//验证码失效
                 [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.8];
                
                [weakSelf.sureButton setBackgroundColor:[UIColor colorWithHexString:@"#ce0d0d"]];
                [weakSelf.sureButton setTitle:@"重新发送验证码" forState:UIControlStateNormal];
                weakSelf.sureButton.userInteractionEnabled = YES;
                weakSelf.verifyField.text = @"";
                
            }else{
                [weakSelf shakeAnimationForView:self.verifyBgview];
                [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.8];
            }
        }
    }];
}

//验证码倒计时
NSInteger TIMECOUNT =120;
- (void)countDownAction:(UIButton *)btn {
    __block NSInteger second = TIMECOUNT;
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second == 0) {
                self.sureButton.userInteractionEnabled = YES;
                [self.sureButton setTitle:[NSString stringWithFormat:@"发送验证码"] forState:UIControlStateNormal];
                second = TIMECOUNT;
                dispatch_cancel(timer);
            } else {
                self.sureButton.userInteractionEnabled = NO;
                [self.sureButton setTitle:[NSString stringWithFormat:@"重新发送(%ld)",second] forState:UIControlStateNormal];
                second--;
            }
        });
    });
    dispatch_resume(timer);
}

//输错验证码抖动效果
- (void)shakeAnimationForView:(UIView *) view{
    // 获取到当前的View
    CALayer *viewLayer = view.layer;
    // 获取当前View的位置
    CGPoint position = viewLayer.position;
    // 移动的两个终点位置
    CGPoint x = CGPointMake(position.x + 10, position.y);
    CGPoint y = CGPointMake(position.x - 10, position.y);
    // 设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    // 设置运动形式
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    // 设置开始位置
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    // 设置结束位置
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    // 设置自动反转
    [animation setAutoreverses:YES];
    // 设置时间
    [animation setDuration:.06];
    // 设置次数
    [animation setRepeatCount:3];
    // 添加上动画
    [viewLayer addAnimation:animation forKey:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
